package com.agricultural.machine.user;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 用户会话管理器类
 */


public class UserSessionManager {
    private static UserSessionManager instance;
    private final Map<String, UserSession> sessions;
    private final int sessionTimeoutMinutes;
    private final ScheduledExecutorService scheduler;
    
    private UserSessionManager() {
        this.sessions = new HashMap<>();
        this.sessionTimeoutMinutes = 30; // 默认30分钟超时
        this.scheduler = Executors.newSingleThreadScheduledExecutor();
        
        // 定期清理过期会话
        scheduler.scheduleAtFixedRate(
            this::cleanExpiredSessions, 
            5, 
            5, 
            TimeUnit.MINUTES
        );
    }
    
    public static synchronized UserSessionManager getInstance() {
        if (instance == null) {
            instance = new UserSessionManager();
        }
        return instance;
    }
    
    /**
     * 创建新会话
     */
    public UserSession createSession(String username, UserRole role) {
        UserSession session = new UserSession(username, role);
        sessions.put(session.getSessionId(), session);
        System.out.println("创建新会话：" + session.getSessionId() + " 用户：" + username);
        return session;
    }
    
    /**
     * 获取会话
     */
    public Optional<UserSession> getSession(String sessionId) {
        UserSession session = sessions.get(sessionId);
        if (session != null && session.isActive()) {
            if (session.isExpired(sessionTimeoutMinutes)) {
                session.setActive(false);
                return Optional.empty();
            }
            session.updateLastAccessTime();
            return Optional.of(session);
        }
        return Optional.empty();
    }
    
    /**
     * 终止会话
     */
    public boolean terminateSession(String sessionId) {
        UserSession session = sessions.get(sessionId);
        if (session != null) {
            session.setActive(false);
            sessions.remove(sessionId);
            System.out.println("终止会话：" + sessionId);
            return true;
        }
        return false;
    }
    
    /**
     * 获取当前活跃会话数量
     */
    public int getActiveSessionCount() {
        return (int) sessions.values().stream()
            .filter(UserSession::isActive)
            .count();
    }
    
    /**
     * 清理过期会话
     */
    private void cleanExpiredSessions() {
        int expiredCount = 0;
        for (UserSession session : sessions.values()) {
            if (session.isActive() && session.isExpired(sessionTimeoutMinutes)) {
                session.setActive(false);
                expiredCount++;
            }
        }
        
        // 从Map中移除过期会话
        sessions.entrySet().removeIf(entry -> !entry.getValue().isActive());
        
        if (expiredCount > 0) {
            System.out.println("已清理 " + expiredCount + " 个过期会话");
        }
    }
} 